<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { transactionDB } from '@/utils/database'
import type { Transaction } from '@/types'
import { ACCOUNT_TYPES, CATEGORY_ICONS } from '@/types'
import { showToast } from 'vant'
import dayjs from 'dayjs'

const router = useRouter()
const route = useRoute()

const loading = ref(false)
const transactions = ref<Transaction[]>([])

const categoryId = ref(parseInt(route.query.categoryId as string))
const categoryName = ref(route.query.categoryName as string)
const startDate = ref(route.query.startDate as string)
const endDate = ref(route.query.endDate as string)

onMounted(async () => {
  await loadTransactions()
})

const loadTransactions = async () => {
  try {
    loading.value = true
    const res: any = await transactionDB.getAll({
      categoryId: categoryId.value,
      startDate: startDate.value,
      endDate: endDate.value
    })
    
    if (res.status === 'success' && res.data) {
      transactions.value = res.data.transactions || []
    }
  } catch (error) {
    console.error('加载交易记录失败:', error)
    showToast('加载失败')
  } finally {
    loading.value = false
  }
}

// 总金额
const totalAmount = computed(() => {
  return transactions.value.reduce((sum, t) => sum + t.amount, 0)
})

// 按日期分组
const groupedTransactions = computed(() => {
  const groups: { [key: string]: Transaction[] } = {}
  
  transactions.value.forEach(transaction => {
    const dateKey = dayjs(transaction.date).format('YYYY-MM-DD')
    if (!groups[dateKey]) {
      groups[dateKey] = []
    }
    groups[dateKey].push(transaction)
  })
  
  return Object.entries(groups)
    .map(([date, transactions]) => ({
      date,
      transactions,
      dayTotal: transactions.reduce((sum, t) => sum + t.amount, 0)
    }))
    .sort((a, b) => b.date.localeCompare(a.date))
})

const formatAmount = (amount: number) => {
  return amount.toFixed(2)
}

const formatDateDisplay = (date: string) => {
  const d = dayjs(date)
  const today = dayjs()
  const yesterday = dayjs().subtract(1, 'day')
  
  if (d.isSame(today, 'day')) {
    return '今日'
  } else if (d.isSame(yesterday, 'day')) {
    return '昨日'
  } else {
    const weekdays = ['日', '一', '二', '三', '四', '五', '六']
    return `${d.format('MM月DD日')} 周${weekdays[d.day()]}`
  }
}

const formatTime = (date: string | Date) => {
  return dayjs(date).format('HH:mm')
}

const onTransactionClick = (transaction: Transaction) => {
  router.push(`/edit/${transaction.id}`)
}
</script>

<template>
  <div class="category-detail-view">
    <van-nav-bar 
      :title="categoryName" 
      left-arrow 
      @click-left="router.back()" 
    />

    <!-- 统计卡片 -->
    <div class="summary-card">
      <div class="summary-item">
        <div class="label">总计</div>
        <div class="value">¥{{ formatAmount(totalAmount) }}</div>
      </div>
      <div class="summary-item">
        <div class="label">笔数</div>
        <div class="value">{{ transactions.length }}</div>
      </div>
      <div class="summary-item">
        <div class="label">均值</div>
        <div class="value">¥{{ transactions.length > 0 ? formatAmount(totalAmount / transactions.length) : '0.00' }}</div>
      </div>
    </div>

    <div v-if="loading" class="loading">
      <van-loading />
    </div>

    <div v-else-if="groupedTransactions.length === 0" class="empty">
      <van-empty description="暂无交易记录" />
    </div>

    <div v-else class="transaction-groups">
      <div 
        v-for="group in groupedTransactions" 
        :key="group.date"
        class="date-group"
      >
        <!-- 日期标题 -->
        <div class="date-header">
          <span class="date-text">{{ formatDateDisplay(group.date) }}</span>
          <span class="day-total">¥{{ formatAmount(group.dayTotal) }}</span>
        </div>
        
        <!-- 该日的交易列表 -->
        <div class="transaction-list">
          <div 
            v-for="transaction in group.transactions" 
            :key="transaction.id"
            class="transaction-item"
            @click="onTransactionClick(transaction)"
          >
            <div class="transaction-info">
              <div class="transaction-desc">
                {{ transaction.description || ACCOUNT_TYPES[transaction.account] }}
              </div>
              <div class="transaction-time">
                {{ formatTime(transaction.date) }}
              </div>
            </div>
            
            <div class="transaction-amount" :class="transaction.type">
              {{ transaction.type === 'income' ? '+' : '-' }}{{ formatAmount(transaction.amount) }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.category-detail-view {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 60px;
}

.summary-card {
  display: flex;
  background: #fff;
  padding: 20px 16px;
  margin-bottom: 12px;
}

.summary-item {
  flex: 1;
  text-align: center;
}

.summary-item .label {
  font-size: 13px;
  color: #999;
  margin-bottom: 8px;
}

.summary-item .value {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.empty {
  padding: 60px 0;
}

.transaction-groups {
  padding: 0 16px;
}

.date-group {
  margin-bottom: 16px;
}

.date-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  font-size: 14px;
}

.date-text {
  font-weight: 500;
  color: #666;
}

.day-total {
  color: #1989fa;
  font-weight: 500;
}

.transaction-list {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
}

.transaction-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
  transition: background-color 0.2s;
}

.transaction-item:last-child {
  border-bottom: none;
}

.transaction-item:active {
  background-color: #fafafa;
}

.transaction-info {
  flex: 1;
}

.transaction-desc {
  font-size: 15px;
  color: #333;
  margin-bottom: 6px;
}

.transaction-time {
  font-size: 13px;
  color: #999;
}

.transaction-amount {
  font-size: 18px;
  font-weight: bold;
  margin-left: 16px;
}

.transaction-amount.income {
  color: #07c160;
}

.transaction-amount.expense {
  color: #ff4444;
}
</style>

